import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { useState } from 'react'
import { AtList, AtListItem, AtButton, AtMessage } from 'taro-ui'
import { debtorService } from '../../utils/cloud'

export default function Debtor() {
  const [debtors, setDebtors] = useState([])
  const [loading, setLoading] = useState(false)

  // 分类映射
  const categoryMap = {
    bank: '银行',
    loan: '小贷',
    friend: '亲友',
    credit: '信用卡'
  }

  // 获取债务人列表
  const fetchDebtors = async () => {
    try {
      setLoading(true)
      const result = await debtorService.getDebtors()

      if (result.success) {
        setDebtors(result.data)
      } else {
        throw new Error(result.error)
      }
    } catch (error) {
      console.error('获取债务人列表失败:', error)
      Taro.atMessage({
        message: '获取债务人列表失败',
        type: 'error'
      })
    } finally {
      setLoading(false)
    }
  }

  // 页面显示时获取数据
  Taro.useDidShow(() => {
    fetchDebtors()
  })

  const handleAddDebtor = () => {
    Taro.navigateTo({ url: '/pages/debtorInfo/index' })
  }

  const handleViewDetail = id => {
    Taro.navigateTo({ url: `/pages/debtorInfo/index?id=${id}` })
  }

  return (
    <View className="min-h-screen bg-gray-100 pb-20">
      <AtMessage />

      {/* 加载状态 */}
      {loading && (
        <View className="flex justify-center items-center py-4">
          <View className="text-gray-500">加载中...</View>
        </View>
      )}

      {/* 债务人列表 */}
      <View className="bg-white shadow-sm">
        {debtors.length > 0 ? (
          <AtList>
            {debtors.map(debtor => (
              <AtListItem
                key={debtor._id}
                title={debtor.name}
                note={`卡号尾号: ${debtor.cardNumber.slice(-4)} | 分类: ${categoryMap[debtor.category] || '未知'}`}
                extraText={debtor.remark}
                onClick={() => handleViewDetail(debtor._id)}
                arrow="right"
                className="border-b border-gray-100 last:border-b-0"
              />
            ))}
          </AtList>
        ) : (
          !loading && (
            <View className="flex justify-center items-center py-8">
              <View className="text-gray-500">暂无债务人数据</View>
            </View>
          )
        )}
      </View>

      {/* 添加按钮 */}
      <View className="fixed bottom-4 left-4 right-4">
        <AtButton
          onClick={handleAddDebtor}
          className="bg-blue-500 hover:bg-blue-600 text-white shadow-lg"
        >
          添加债务人
        </AtButton>
      </View>
    </View>
  )
}
